﻿/**********************************************************************
*创建人：蔡水明
*创建时间：2018/4/2 18:48:47
*说明：<Function>
/**********************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utilities
{
    public class FileHelper
    {
        /// <summary>
        /// 判断文件是否被占用
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool IsFileInUse(string fileName)
        {
            if (File.Exists(fileName) == false) return false;
            bool inUse = true;
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                inUse = false;
            }
            catch (Exception e)
            {
                LogHelper.Error(e);
            }
            finally
            {
                if (fs != null)
                    fs.Close();
            }
            return inUse;//true表示正在使用,false没有使用    
        }

        public static bool DeleteFiles(string path)
        {
            if (Directory.Exists(path) == false)
                return true;
            DirectoryInfo dir = new DirectoryInfo(path);
            FileInfo[] files = dir.GetFiles();
            try
            {
                foreach (var item in files)
                {
                    File.Delete(item.FullName);
                }
                if (dir.GetDirectories().Length != 0)
                {
                    foreach (var item in dir.GetDirectories())
                    {
                        DeleteFiles(dir.ToString() + "\\" + item.ToString());
                    }
                }
                Directory.Delete(path);
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return false;

            }



        }
    }
}
